import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/user_api.dart';
import 'package:sainbainu/common/repositories/user_repository.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/values/sizes.dart';

import 'index.dart';

/// 头部额外高度（不含appbar）
const double kHeaderExtarHeight = 390.0;

class MyController extends GetxController
    with GetSingleTickerProviderStateMixin {
  MyController();

  final state = MyState();

  Worker? worker;

  @override
  void onInit() {
    super.onInit();

    state.tabController = TabController(length: 4, vsync: this);

    state.scrollController = ScrollController();
    state.scrollController.addListener(() {
      calcCollapsed();
      calcTitleOpacity();
    });
    state.userRepository = UserRepository(UserApi());

    getUserDetail();

    worker = ever(UserService.to.isLogin, (isLogin) {
      if (isLogin) {
        getUserDetail();
      }
    });
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.scrollController.dispose();
    state.tabController.dispose();
    worker?.dispose();
  }

  /// 计算上滑头部完全折叠
  calcCollapsed() {
    bool isCollapsed = state.scrollController.offset >=
        kProfileCoverHeight - kProfileTabbarHeight - kToolbarHeight;
    if (state.isCollapsed.value != isCollapsed) {
      state.isCollapsed.value = isCollapsed;
    }
  }

  /// 完全展开到开始渐变时的高度
  calcTitleOpacity() {
    double collapsedHeight = kProfileCoverHeight -
        kToolbarHeight -
        kToolbarHeight -
        kProfileTabbarHeight;

    if (state.scrollController.offset >= collapsedHeight) {
      // 计算上滑标题透明度
      double opacity = min(
        (state.scrollController.offset - collapsedHeight) / kToolbarHeight,
        1,
      );
      if (state.titleOpacity.value != opacity) {
        state.titleOpacity.value = opacity;
      }
    } else {
      if (state.titleOpacity.value != 0.0) {
        state.titleOpacity.value = 0.0;
      }
    }
  }

  /// 详情
  Future<void> getUserDetail() async {
    var userDetail = await state.userRepository.userInfo();

    state.userInfoResponse = userDetail;
    update(['userDetail']);
  }
}
